package cn.paul.wechatshop.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;

import java.io.Serializable;

import static com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion.NON_NULL;


/**
 * Created by 徐凌峰 on 2017/9/23 0023.
 */
@Getter
// 保证了null数据不会返回给前端
//@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class ServerResponse<T> implements Serializable {

    /**
     * 该类用于封装返回的对象为JSON
     */
    private int status;
    private String msg;
    /**
     * 此处采用泛型设计,便于以后返回不同的类型
     */
    private T data;

    private ServerResponse() {
    }

    private ServerResponse(int status) {
        this.status = status;
    }

    private ServerResponse(int status, T data) {
        this.status = status;
        this.data = data;
    }


    private ServerResponse(int status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    private ServerResponse(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    /**
     * 返回成功的状态码
     * @param <T>
     * @return
     */
    public static <T> ServerResponse<T> createBySuccess() {
        return new ServerResponse<T>(Const.ResponseCode.SUCCESS.getCode());
    }

    /**
     * 返回成功的字符串信息
     * @param msg
     * @param <T>
     * @return
     */

    public static <T> ServerResponse<T> createBySuccessMessage(String msg) {
        return new ServerResponse<T>(Const.ResponseCode.SUCCESS.getCode(), msg);
    }

    /**
     * 返回成功后带的泛型数据
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ServerResponse<T> createBySuccess(T data) {
        return new ServerResponse<T>(Const.ResponseCode.SUCCESS.getCode(), data);
    }

    public static <T> ServerResponse<T> createBySuccess(String msg, T data) {
        return new ServerResponse<T>(Const.ResponseCode.SUCCESS.getCode(), msg, data);
    }

    public static <T> ServerResponse<T> createByError() {
        return new ServerResponse<T>(Const.ResponseCode.ERROR.getCode(), Const.ResponseCode.ERROR.getDesc());
    }

    public static <T> ServerResponse<T> createByErrorMessage(String errorMsg) {
        return new ServerResponse<T>(Const.ResponseCode.ERROR.getCode(), errorMsg);
    }

    public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode, String errorMessage) {
        return new ServerResponse<T>(errorCode, errorMessage);
    }



    //该注解的方法或者字段不会作为json返回出去
    @JsonIgnore
    public boolean isSuccess() {
        return this.status == Const.ResponseCode.SUCCESS.getCode();
    }
}
